package sevlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/getAuthorInfo")
public class GetAuthorInfo extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.先拿到请求中的blogId
        String blogId = req.getParameter("blogId");
        //判断是否合法
        if(blogId == null) {
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write("请求中必须有blogId");
            return;
        }
        //2.在blog表查找是否有对应的blog对象
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
        if(blog == null) {
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write("未找到当前博客");
            return;
        }
        //3.在User表中查找是否有对应的user对象
        UserDao userDao = new UserDao();
        User user = userDao.getUserById(blog.getUserId());
        if(user == null) {
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write("当前用户未找到");
            return;
        }
        //4.把这个user对象返回到服务器这边
        //两个都有说明当前用户已经登录
        resp.setContentType("application/json;charset=utf8");
        //注意密码不要泄露了
        user.setPassword("");
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
